package com.atguigu.juc.locks;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author yanglin
 * @create 2024-02-02 16:08 星期五
 * description:  读写锁
 */
public class ReadWriteLockDemo {

    /**
     * 读写锁定义为：一个资源能够被多个读资源访问，或者被一个写线程访问，但不能同时存在读写线程（读写互斥  读读共享）
     *      
     */

    public static void main(String[] args) {
        MyResource myResource = new MyResource();
        for (int i = 0; i < 10; i++) {
            int temp = i;
            new Thread(() -> {
                myResource.write(temp +"", temp +"");
            }).start();
        }

        for (int i = 0; i < 10; i++) {
            int tem = i;
            new Thread(() -> {
                myResource.read(tem+"");
            }).start();
        }

        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        for (int i = 0; i < 3; i++) {
            int temp = i;
            new Thread(() -> {
                myResource.write(temp +"", temp +"");
            },"新写锁线程-》" + temp).start();
        }
    }
    
    
}


class MyResource {   //资源类，模拟一个简单缓存
    Map<String,String> map = new HashMap<>();
    Lock lock = new ReentrantLock();
    ReadWriteLock rwLock = new ReentrantReadWriteLock();
    
    public void write(String key,String value){
//        lock.lock();
        rwLock.writeLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + "\t" + "正在写入");
            map.put(key,value);
            try {
                TimeUnit.MILLISECONDS.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "\t 完成写入");
        }finally {
//            lock.unlock();
            rwLock.writeLock().unlock();
        }
    }
    
    public void read(String key){
//        lock.lock();
        rwLock.readLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + "\t 正在读取");
            String value = map.get(key);
//            try {
//                TimeUnit.MILLISECONDS.sleep(200);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
            //演示读锁没有完成之前，写锁无法获得
            try {
                TimeUnit.MILLISECONDS.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "\t 完成读取   " + value);
        }finally {
//            lock.unlock();
            rwLock.readLock().unlock();
        }
    }
}
